package com.star.pickstarbackend.controller;

import com.star.pickstarbackend.pojo.Result;
import com.star.pickstarbackend.pojo.User;
import com.star.pickstarbackend.service.UserService;
import com.star.pickstarbackend.utils.JwtUtil;
import com.star.pickstarbackend.utils.Md5Util;
import com.star.pickstarbackend.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
     @Autowired
     private UserService userService;

     @PostMapping("/register")
     public Result register(@RequestParam @Pattern(regexp = "^\\S{5,16}$") String username,
                            @RequestParam @Pattern(regexp = "^\\S{5,16}$") String password ,
                            @RequestParam String email,
                            @RequestParam String phone,
                            @RequestParam String realname,
                            @RequestParam String role,
                            @RequestParam String avatar) {
          // 查询用户
          User u = userService.findByUsername(username);
          if (u == null) {
               userService.register (username,password,email,phone,realname,role,avatar);
               return Result.success();
          }
          else {
               return Result.error("用户名已存在");
          }
     }

     @PostMapping("/login")
     public Result<String> login(@RequestParam @Pattern(regexp = "^\\S{5,16}$") String username,
                         @RequestParam @Pattern(regexp = "^\\S{5,16}$") String password) {
            // 查询用户
          User loginUser = userService.findByUsername(username);
          if (loginUser == null){
               return Result.error("用户不存在");
          }
          if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
               Map<String,Object> claims = new HashMap<>();
               claims.put("id",loginUser.getId());
               claims.put("username",loginUser.getUsername());
               String token = JwtUtil.genToken(claims);
               return Result.success(token);
          }
          return Result.error("密码错误");
     }

        // 获取用户信息
        @GetMapping("/info")
        public Result<User> userInfo() {
             Map<String, Object> map = ThreadLocalUtil.get();
             if (map == null || !map.containsKey("username")) {
                  return Result.error("用户信息未找到");
             }
             String username = (String) map.get("username");
             User user = userService.findByUsername(username);
             return Result.success(user);
        }


        //更新用户信息
     @PutMapping("/update")
     public Result update(@RequestBody @Validated User user){
          userService.update(user);
          return Result.success();
     }

     //更新用户头像
     @PatchMapping("/updateAvatar")
     public Result updateAvatar(@RequestParam @URL String avatarUrl ,@RequestParam Integer id){
          userService.update(avatarUrl,id);
          return Result.success();
     }

     //更新密码
     @PatchMapping("/updatePwd")
     public Result updatePwd(@RequestBody Map<String,String> params){
          //校验参数
          String oldPwd = params.get("old_pwd");
          String newPwd = params.get("new_pwd");
          String rePwd = params.get("re_pwd");

          if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
               return Result.error("缺少必要参数");
          }
          //校验原密码是否正确
          //调用userService的原密码与oldPwd比对
          Map<String,Object> map = ThreadLocalUtil.get();
          String username = (String) map.get("username");
          User loginUser = userService.findByUsername(username);
          //调用service层完成密码更新
          if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
               return Result.error("原密码错误");
          }
          //校验newPwd和rePwd是否一致
          if(!newPwd.equals(rePwd)){
               return Result.error("新密码不一致");
          }
          userService.updatePwd(newPwd);
          return Result.success();
     }
}